<?php
function ghf_session_open($save_path, $session_name){
  return(true);
}

function ghf_session_close(){
  return(true);
}

function ghf_session_read($id){
	$data = $_ENV['db']->get_var(sprintf("SELECT Fdata FROM txb_sessions WHERE Fsid='%s'",$id));
	if($data){
		return $data;
	}
	return "";
}

function ghf_session_write($sid, $sess_data){
	$data = ghf_session_unserializesession($sess_data);
	$uid = 0;
	if(count($data) > 0){
		if(isset($data['Fuid'])){
			$uid = $data['Fuid'];
		}
	}
	$sql = sprintf("REPLACE INTO txb_sessions(Fsid,Fuid,Fdata,Fdateline) VALUES('%s',%d,'%s',%d)",$sid,$uid,$sess_data,time());
	$_ENV['db']->query($sql);
	return true;
}

function ghf_session_destroy($id){
	$_ENV['db']->del_row("txb_sessions",sprintf("Fsid='%s'",$id)); 
	return true;
}

function ghf_session_gc($maxlifetime){
	$_ENV['db']->del_row("txb_sessions","Fdateline<".(time() - $maxlifetime)); 
	return true;
}
/**
 *	解密session的数据
 **/
function ghf_session_unserializesession($data) {
	$result = array();
	if($data){
		$vars = preg_split('/([a-z_A-Z0-9]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
		if(isset($vars) AND is_array($vars) AND count($vars) > 0){
			for($i=0; isset($vars[$i]); $i++) {
				if(isset($vars[$i+1])){					
					$result[$vars[$i++]] = isset($vars[$i])  ? @unserialize(stripslashes(preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $vars[$i]))) : '';   
				}
			}
		}
	}
    return $result;
}

session_set_save_handler("ghf_session_open", "ghf_session_close", "ghf_session_read", "ghf_session_write", "ghf_session_destroy", "ghf_session_gc");
session_start();

